#!/usr/bin/env python

# Written by: Alan Viars, Videntity
# Copyright 2010 - All Rights Reserved

import sys
import datetime
from Tkinter import *
from settings import *
from vipywrap.VID_Omhe import *


try:    
    sys.path.append('/home/chris/django-dev/omhe-dev/blood_pressure_meter')
    from omheparser import omheparser
except:
    print "Warning: Failed to import omhe parser"

class App:
    """ A blood pressure GUI application based on OMHE Microsyntax"""
    """Global Variables"""
    omhe_bp_prefix="bp="
    systolic_str=""
    diastolic_str=""
    pulse_str=""
    omhe_s_d_deliniator="/"
    pulse_deliniator="p"
            
    def __init__(self, master):

        frame = Frame(master, padx=20, pady=20)
        frame["bg"] = '#E9F6DC'
        frame.grid(row=1)
        
        frame2 = Frame(master, padx=115, pady=10)
        frame2["bg"] = '#E9F6DC'
        frame2.grid(row=5)
        
        Heading = Frame(master, padx=0, pady=0)
        Heading["bg"] = 'white'
        Heading.grid(row=0)
        
        H1 = Label(Heading, text="Please Enter Your Blood Pressure", bg="white", fg="#427cce", font = ("Arial", 26, "bold"))
        H1.grid(row=0, column=0)
    
        spinval = StringVar()
        
        l1 = Label(frame, text="Systolic:", bg="#E9F6DC", fg="#427cce", font = ("Arial", 16, "bold"))
        l1.grid(row=1, column=1, sticky=W)
        self.systolicsb = Spinbox(frame, from_=0.0, to=300.0, increment=1)
        self.systolicsb.grid(row=1, column=2, sticky=W)
        self.systolicsb.delete(0)
        self.systolicsb.insert(ANCHOR,"120")
        
         
        l2 = Label(frame, text="Diastolic:", bg="#E9F6DC", fg="#427cce", font = ("Arial", 16, "bold"))
        l2.grid(row=2, column=1, sticky=W)
        self.diastolicsb = Spinbox(frame, from_=0.0, to=300.0, increment=1)
        self.diastolicsb.grid(row=2, column=2, sticky=W)
        self.diastolicsb.delete(0)
        self.diastolicsb.insert(ANCHOR,"85")
        
        l3 = Label(frame, text="Pulse:", bg="#E9F6DC", fg="#427cce", font = ("Arial", 16, "bold"))
        l3.grid(row=3, column=1, sticky=W)
        self.pulsesb = Spinbox(frame, from_=0.0, to=300.0, increment=1)
        self.pulsesb.grid(row=3, column=2, sticky=W)
        self.pulsesb.delete(0)
        self.pulsesb.insert(ANCHOR,"60")
        
        #l4 = Label(frame, text="User ID:", bg="#E9F6DC", fg="#427cce", font = ("Arial", 16, "bold"))
        #l4.grid(row=4, column=1, sticky=W)
        #self.user_ent = Entry(frame, width = 21)
        #self.user_ent.grid(row=4, column=2, sticky=W)
        #self.user_ent.delete(0, END)
        #self.user_ent.insert(0, USER)
        
        l4 = Label(frame, text="Passcode:", bg="#E9F6DC", fg="#427cce", font = ("Arial", 16, "bold"))
        l4.grid(row=4, column=1, sticky=W)
        self.passcode_ent = Entry(frame, width = 21)
        self.passcode_ent.grid(row=4, column=2, sticky=W)
        self.passcode_ent.delete(0, END)
        self.passcode_ent.insert(0, '')
        

        try:
            import serial
            mystate=ACTIVE
        except(ImportError):
            mystate=DISABLED
            print "The serial package was not found. Disabling Meter button."
            
        self.button = Button(frame, text="GET FROM METER", command=self.getFromMeter, state=mystate, width = 21, bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=1, column=3, sticky=E, padx = 20, pady=5)
        
        try:
            import vipywrap
            mystate=ACTIVE
        except(ImportError):
            mystate=DISABLED
            print "The Videntity API package was not found. Disabling Videntity Send."
        self.button = Button(frame, text="SEND VIA VIDENTITY", command=self.sendVidentity, state=mystate, width = 21, bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=2, column=3, sticky=E, padx = 20, pady=5)
        
        try:
            import twitter
            mystate=ACTIVE
        except(ImportError):
            mystate=DISABLED
            print "The Twitter package was not found. Disabling Twitter Send."
        self.button = Button(frame, text="SEND VIA TWITTER", command=self.sendTwitter, state=mystate, width = 21, bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=3, column=3, sticky=E, padx = 20, pady=5)
        
        try:
            mystate=ACTIVE
            self.rfile = open("settings.py","r+")
            

        except:
            mystate=DISABLED
            print "Unable to open settings file."
        
        #self.button = Button(frame, text="SET USER", command=self.setUser, state=mystate,
        #                     width = 21, bg = "white", fg="#427cce", font = 16, highlightbackground = "#427cce")
        #self.button.grid(row=4, column=3, sticky=E, padx = 20, pady=5)
        
        self.button = Button(frame, text="SUBMIT PASSCODE", command=self.verifyPasscode, state=mystate,
                             width = 21, bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=4, column=3, sticky=E, padx = 20, pady=5)
        
        self.button = Button(frame2, text="RESET", command=self.reset, width = 15,bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=0, column=1, pady = 5, padx=5)
        
        self.button = Button(frame2, text="QUIT", command=frame.quit, width = 15,  bg = "white", fg="#427cce", font = ("Arial", 16), highlightbackground = "#427cce")
        self.button.grid(row=0, column=2, pady = 5, padx=5)
        
        
        
        self.firstdot=True
      
    def reset(self):
        self.systolicsb.delete(0,END)
        self.systolicsb.insert(ANCHOR,"120")
        self.diastolicsb.delete(0,END)
        self.diastolicsb.insert(ANCHOR,"85")
        self.pulsesb.delete(0,END)
        self.pulsesb.insert(ANCHOR,"60")
        
    def verifyPasscode(self):
        print "Verifying Passcode"
        
        omhe = Videntity_Omhe(debug = DEBUG,
                              videntity_username = VIDENTITY_USERNAME,
                              videntity_account_number = VIDENTITY_ACCOUNT_NUMBER,
                              videntity_session_password = VIDENTITY_PASSWORD,
                              videntity_server = VID_SERVER)
                            
                            
        
        omhe.account_number = USER#self.user_ent.get()
        
        omhe.one_time_password = self.passcode_ent.get()
    
        #process the omhe message
        omhe.verify()

        #######################################################
        #Videntity logout
        omhe.logout()
        
        if omhe.omhe_message_verified == '1':
            print 'PASSCODE VERIFIED!'
        
        
        
    def setUser(self):
        print "setting user"
        
        self.rfile = open("settings.py","r")
        
        settingslist = []
        for index, line in enumerate(self.rfile):
            #print line
            
            if line[0:4] == "USER":
                settingslist.append("""USER = '%s'"""%self.user_ent.get())
                #settingslist = """USER = '%s'"""%self.user_ent.get()
            else:
                settingslist.append(line)
                #settingslist=line
            #print settingslist
            #self.rfilew.write(settingslist)
        self.rfile.close()
        
        #print settingslist
        
        self.rfilew = open("settings.py","w")
        
        self.rfilew.writelines(settingslist)

        self.rfilew.close()
        
        
        #self.rfile.close()
        
      
    def genOmheStr(self):
        print "generating omhe str"
        self.omhe_str = "%s%s%s%s%s%s" %(self.omhe_bp_prefix, self.systolicsb.get(),
                              self.omhe_s_d_deliniator, self.diastolicsb.get(),
                              self.pulse_deliniator,
                              self.pulsesb.get())
        print 'omhe string -> %s' %self.omhe_str
        
    def getFromMeter(self):
        print "get from meter"
        import serial
        ser = serial.Serial(serial_port, xonxoff=1)
        """pop up a window and tell the person to press start on the device"""
        print ser
        #tkMessageBox.showinfo("Grab your Blood Pressure",
        #                      "Place the cuff around your arm, and press START on the meter.")
        print "waiting for device reading..."
        s = ser.read(10)
        print "Complete!"
        print s
        sys=s[2:4]
        dia=s[4:6]
        pul=s[6:8]
        
        sys=int(sys,16)
        print sys
        dia=int(dia,16)
        print dia
        pul=int(pul,16)
        print pul
        sys =sys+dia
        print sys
        print "%s/%sp%s" %(sys,dia,pul)
        self.systolicsb.delete(0,END)
        self.systolicsb.insert(ANCHOR,sys)
        self.diastolicsb.delete(0,END)
        self.diastolicsb.insert(ANCHOR,dia)
        self.pulsesb.delete(0,END)
        self.pulsesb.insert(ANCHOR,pul)
        
    def sendVidentity(self):
        print "send via videntity"
        
        #generate the omhe string
        self.genOmheStr()
        
        omhe = Videntity_Omhe(debug = DEBUG,
                              videntity_username = VIDENTITY_USERNAME,
                              videntity_account_number = VIDENTITY_ACCOUNT_NUMBER,
                              videntity_session_password = VIDENTITY_PASSWORD,
                              videntity_server = VID_SERVER)
                            
                            
        import uuid
        omhe.transaction_control_number = uuid.uuid4()
        
        print USER
        omhe.account_number = USER#self.user_ent.get()
        

        omhe.message = self.omhe_str
        omhe.date_created = datetime.datetime.now()
        
        omhe.sms_execute = '0'
        omhe.twitter_execute = '1'
        omhe.authenticate = '1'
        omhe.authenticate_transmission = AUTHENTICATION_TRANSMISSION #'text' or 'voice'
        
        #process the omhe message
        omhe.process()

        #######################################################
        #Videntity logout
        omhe.logout()
        
        if omhe.omhe_message_response:
            print 'BLOOD PRESSURE SENT!'
        
    def sendTwitter(self):
        print "send via twitter"
        #self.progressbar.set(value=25.0)
        
        #generate the omhe string
        self.genOmheStr()
        
        try:
            api = twitter.Api(username=twitterid, password=twitterpass)
            result = api.PostDirectMessage(twitterreceiver, self.omhe_str)
            if result:
                print "Successfuly sent DM"
                self.reset()
            else:
                print "There was a problem sending your DM tweet.  Please check user, pass and that the reciever is following you."
        except:
            print "There was a problem sending your DM tweet. Please check user, pass and that the reciever is following you."

    
root = Tk()
root.title("Blood Pressure Tool")
root["padx"] = 30
root["pady"] = 30
root["bg"] = 'white'

app = App(root)

root.mainloop()
